import { NavigationGuardNext, RouteLocationNormalized, Router } from 'vue-router';
import { CacheEnum } from '@/enum/cacheEnum';
import userStore from '@/store/user-store';
import menuStore from '@/store/menu-store';
import storage from '@/utils/storage';
import utils from '@/utils';

class Guard {
  constructor(private router: Router) {}
  public run() {
    this.router.beforeEach(this.beforeEach.bind(this));
  }

  // 对登录的路由进行校验
  private async beforeEach(to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) {
    if (to.name === 'login') next();
    if (this.isNeedLogin(to) == true) {
      return next({ name: 'login' });
    } else if (this.isGuest(to) == false) {
      return from;
    } else {
      // 等用户资料获取后再渲染
      await this.getUserInfo();

      return next();
    }
  }

  // 获取用户信息
  private getUserInfo() {
    return userStore().getUserInfo();
  }
  // 获取token
  private getToken(): string | null {
    return storage.get(CacheEnum.TOKEN_NAME);
  }

  // 游客判断
  private isGuest(route: RouteLocationNormalized) {
    return Boolean(!route.meta.guest || (route.meta.auth && this.getToken()));
  }

  /**
   * 登录判断
   * 1.auth为true且token不存在
   * 如果访问的页面需要auth且token不存在
   * @param route
   * @param token
   * @returns
   */
  private isNeedLogin(route: RouteLocationNormalized) {
    const isNeed = Boolean(route.meta.auth && !this.getToken());
    if (isNeed) {
      // 存储被拦截的路由
      utils.storage.set(CacheEnum.REDIRECT_ROUTE_NAME, route.name);
    }
    return isNeed;
  }
}
export default (router: Router) => {
  new Guard(router).run();
};
